package org.bjf.modules.sys.web.controller;

import lombok.Data;
import lombok.experimental.Accessors;
import org.bjf.exception.ServiceException;
import org.bjf.modules.core.web.core.LoginInfo;
import org.bjf.modules.sys.bean.SysUser;
import org.bjf.modules.sys.enums.SysMsgCode;
import org.bjf.modules.sys.query.SysUserQuery;
import org.bjf.modules.sys.service.SysUserService;
import org.bjf.security.PasswordUtil;
import org.bjf.security.satoken.SaTokenAdminUtil;
import org.bjf.utils.IpUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;

/**
 * @author bjf
 */
@RestController
@Validated
@RequestMapping("admin")
public class SysController {

    @Resource
    private SysUserService sysUserService;

    @RequestMapping("login")
    public LoginResp login(@RequestParam @NotBlank String username,
                           @RequestParam @NotBlank String password, HttpServletRequest request) {
        //===1、验证用户名密码
        SysUserQuery query = new SysUserQuery().setUsername(username);
        SysUser loginUser = sysUserService.getOne(query);
        if (loginUser == null || !PasswordUtil.valid(password, loginUser.getPassword())) {
            throw new ServiceException(SysMsgCode.USER_WRONG);
        }

        //===2、登录成功，生成token并将登录用户信息写入redis
        SaTokenAdminUtil.login(loginUser.getId());
        String accessToken = SaTokenAdminUtil.getTokenValue();
        Long userId = loginUser.getId();
        String ip = IpUtil.getIp(request);
        LoginInfo loginInfo = LoginInfo.buildLoginInfo(userId, loginUser.getUsername(), ip);
        // 数据是会放到redis
        SaTokenAdminUtil.getTokenSession().set("loginInfo", loginInfo);
        // 15天过期
//        long timeout = 60 * 30;
//        String userKey = UserRedisKey.TOKEN_ADMIN.as(accessToken);
//        redis.setObj(userKey, loginInfo, timeout);

        //===3、返回登录信息-accessToken
        LoginResp loginResp = new LoginResp();
        loginResp.setAccessToken(accessToken);
        return loginResp;
    }

    @RequestMapping("logout")
    public void logout() {
        SaTokenAdminUtil.logout();
    }

    @Data
    @Accessors(chain = true)
    private static class LoginResp {

        private String accessToken;
    }
}
